
import tags

class base_gen:
    def __init__(self, t, name):
        self.mtag = t
        self.fname = name
        self.id = 0

    def get_id(self):
        self.id += 1
        return "obj" + str(self.id)
        

class dynamic_gen(base_gen):
    def kids_gen(self, kids):
        if len(kids) == 0:
            return "[]"
        ret = "[" + kids[0]
        for k in kids[1:]:
            ret += ", " + k
        return ret + "]"

    def code_gen(self, tag):
        mycode = ""
        mykids = [] # All the objXXX
        for c in tag.children:
            ret = self.code_gen(c)
            mycode += ret[0]
            mykids.append(ret[1])

        myid = self.get_id()
        mycode += ("import " + tag.__module__ + "\n" +
                   myid + " = " +
                   tag.__module__ + "." + tag.__class__.__name__ +
                   "(" + self.kids_gen(mykids) + ")\n")
            
        return [mycode, myid]

                

    def out(self):
        fout = open(self.fname, 'w')
        fout.write("#!/usr/bin/python\n\n")

        code = self.code_gen(self.mtag)
        fout.write(code[0])
        fout.write("print " + code[1] + ".toHTML()")

    
    
